/*
 * @Description:路由基础配置
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-22 10:58:11
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-21 18:07:29
 */
import Layout from '@/layout/index.vue'
export const baseRouterConfig = {
  path: '/',
  component: Layout,
  redirect: '/dashboard',
  children: [
    // {
    //   path:"sub02",
    //   component: (resolve) => require(['@/components/otherSystem/index.vue'], resolve)
    // },

  ]
}
const defaultTreeConfig = {
  id: 'id',
  pId: 'pId',
  children: 'children'
}
/**
 * @description: 根据菜单变换路由
 * @param {Array} menuData api菜单
 * @return {Routes} 可渲染的路由
 * @author: kafei
 */
export const BfsTreeData = (treeData, cb, treeConfig) => {
  const config = { ...defaultTreeConfig, ...treeConfig }
  // const tagetData = cloneDeep(treeData)
  if (!treeData || !treeData.length) {
    return []
  }
  let stack = []
  for (let i = 0; i < treeData.length; i++) {
    stack.push(treeData[i])
  }
  let item = null
  while (stack.length) {
    item = stack.shift()
    if (cb) {
      const result = cb(item)
      if (result) {
        return result
      }
    }
    if (item[config.children] && item[config.children].length > 0) {
      stack = stack.concat(item[config.children])
    }
  }
  return treeData
}
export const getParentPath = (menuData, id) => {
  const target = BfsTreeData(menuData, (v) => {
    if (v.id === id) {
      return v
    }
  }, { pId: 'parentId' })
  return target && Object.keys(target).length > 0 ? target.path : ''
}
export const routerPermisson = (menuData) => {
  const childItem = menuData.reduce((cur, next) => {
    if (next.cilentType === '0') {
      const json = {
        path: next.parentId !== 0 ? `${getParentPath(menuData, next.parentId)}/${next.path}` : next.path,
        component: (resolve) => require([`@/${next.componentPath}/index.vue`], resolve),
        name: next.enName,
        meta: {
          title: next.mName,
          icon: next.icon,
          affix: true,
          cilentType: next.cilentType
        }
      }
      cur.push(json)
      return cur
    }
    return cur
  }, [])
  baseRouterConfig.children = childItem
  return baseRouterConfig
}

export const listToTree = (list, treeConfig, callBack) => {
  const config = { ...defaultTreeConfig, ...treeConfig }
  const info = list.reduce((map, node) => {
    if (!map[node[config.id]]) {
      map[node[config.id]] = node
      node[config.children] = []
    }
    return map
  }, {})
  return list.filter(v => {
    callBack && callBack(v)
    if (info[v[config.pId]]) {
      info[v[config.pId]][config.children].push(v)
    }
    return !v[[config.pId]]
  })
}
